package org.ielts.service;

import java.util.ArrayList;
import java.util.Date;

import org.ielts.domain.base.Lesson;
import org.ielts.domain.base.SignCourse;
import org.ielts.domain.log.OrderLessonLog;
import org.ielts.domain.report.LessonWithListenerCount;
import org.ielts.domain.security.User;
import org.ielts.repository.LessonRepository;
import org.ielts.repository.OrderLessonLogRepository;
import org.ielts.repository.SignCourseRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.yifeng.ProfileContext;
import com.yifeng.profile.Profile;

@Service
public class OrderLessonService {

	@Autowired
	OrderLessonLogRepository orderLessonLogRepository;

	@Transactional
	public Iterable<OrderLessonLog> findBySignCourse(String signCourseId) {

		Iterable<OrderLessonLog> orderLessonLogs = orderLessonLogRepository.findBySignCourse(signCourseId);

		return orderLessonLogs;
	}

	@Transactional
	public OrderLessonLog findOne(String id) {
		OrderLessonLog orderLessonLog = orderLessonLogRepository.findOne(id);

		return orderLessonLog;
	}

	@Transactional
	public Iterable<OrderLessonLog> findOrderLessonLogByLesson(String id) {
		Iterable<OrderLessonLog> orderLessonLogs = orderLessonLogRepository.findOrderLessonLogByLesson(id);
		return orderLessonLogs;
	}

	@Autowired
	SignCourseRepository signCourseRepository;

	@Transactional
	public OrderLessonLog orderHistoryLesson(String signCourseId, String title, Date beginTime, Date endTime) {
		User creator = (User) Profile.getInstance().getUser();
		SignCourse signCourse = signCourseRepository.findOne(signCourseId);

		OrderLessonLog orderLessonLog = new OrderLessonLog();
		orderLessonLog.setCreator(creator);

		orderLessonLog.setTitle(title);

		orderLessonLog.setSignCourse(signCourse);
		orderLessonLog.setStudent(signCourse.getStudent());
		orderLessonLog.setBeginTime(beginTime);
		orderLessonLog.setEndTime(endTime);

		orderLessonLogRepository.save(orderLessonLog);

		return orderLessonLog;
	}

	@Transactional
	public long countByLesson(String id) {
		long count = orderLessonLogRepository.countByLesson(id);
		return count;
	}
}
